import { ApiCall, WsClient } from "tsrpc";
import { ecs } from "../../../core/ecs/ECS";
import { ReqRegRoom, ResRegRoom } from "../../../tsrpc/shared/protocols/hall/PtlRegRoom";
import { ECSEntity } from "../../../core/ecs/ECSEntity";
import { HallService } from "../HallService";
import { CommonFactory } from "../../../module/common/CommonFactory";
import { serviceProto as RoomServiceProto, ServiceType as RoomServiceType } from "../../../tsrpc/shared/protocols/RoomServiceProto";
import chalk from "chalk";

@ecs.register('JoinRoomService')
export class JoinRoomServiceComp extends ecs.Comp {
    call: ApiCall<ReqRegRoom, ResRegRoom> = null!;
    reset(): void { }
}

export class JoinRoomServiceSystem extends ecs.ComblockSystem implements ecs.IEntityEnterSystem {
    async entityEnter(entity: HallService) {
        //目前是只实现同一时间
        const call = entity.get(JoinRoomServiceComp).call
        const wsc = CommonFactory.createWscRoom(call.conn.ip, call.req.port,entity.HallModel.hsHall);
        const irs = {
            name: "房间服务器"+call.req.port,
            wsc: wsc,
        }
        entity.HallModel.roomServiceList.push(irs)

        this.flows(entity, wsc);
        // 自定义消息处理
        this.msgs(wsc, irs);

        const connectRes = await wsc.connect();
        if (!connectRes.isSucc) {//连接失败
            entity.HallModel.roomServiceList.remove(v => v.name === irs.name);
            call.error("无法连接到房间服务器ws",{code:"CONNECT_ERROR"});
            return;
        }

        call.succ({});
        entity.remove(JoinRoomServiceComp);
    }

    /** 自定义管线 */
    private flows(e: HallService, wsc: WsClient<RoomServiceType>) {
        // 管线：客户端断开连接后 - 房间服务器列表中移除断开的房间服务器
        wsc.flows.postDisconnectFlow.push(v => {
            // 客户端断开时，更新对应房间状态
            e.HallModel.roomServiceList.remove(irs => {
                if (irs.wsc === wsc) {
                    e.HallModel.hsHall.logger.log(chalk.red(`房间服务器 ${irs.name} 主动断开`));
                    return true;
                }
                return false;
            });
            return v;
        });
    }

    /** 监听房间服务器消息 */
    private msgs(wscRoom: WsClient<RoomServiceType>, irs: {name:string, wsc:WsClient<RoomServiceType>}) {
        // 监听消息：更新房间状态
        // wscRoom.listenMsg(`admin/RoomUpdateState`, msg => {
        //     irs.state = msg;
        // });
    }
    filter(): ecs.IMatcher {
        return ecs.allOf(JoinRoomServiceComp);
    }

}